package com.bec.serialportscales

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

import android.util.Log
import android.widget.Toast
import com.bec.serialportlibrary.OnDataReceivedListener

import com.bec.serialportlibrary.SerialPortController
import com.bec.serialportlibrary.SerialPortControllerImpl
import com.bec.serialportlibrary.Utils
import com.bec.serialportlibrary.devicetype.DaHuaElectronicScale
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.experimental.xor

class MainActivity : AppCompatActivity(), OnDataReceivedListener {

    private val daHuaElectronicScale = DaHuaElectronicScale()

    private val serialPortController: SerialPortController by lazy { SerialPortControllerImpl(this@MainActivity, daHuaElectronicScale).setOnDataReceivedListener(this@MainActivity) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        daHuaElectronicScale.path = "/dev/ttyS3"

        btnOpen.setOnClickListener {
            try {
                serialPortController.openSerialPortAndReadData()
            } catch (e: Exception) {
                Log.e(this.toString(), e.toString())
            }
        }

        btnClose.setOnClickListener { serialPortController.destroy() }

    }

    override fun onDataReceived(isConnected: Boolean, buffer: ByteArray?, size: Int) {

        if (!isConnected) {
            Log.i("ActivityRead", "ReadThread:连接失败")
            return
        }

        buffer?.let {

            //            val temp = buffer.slice(2..11).toByteArray()
//
//            val a = formatData(buffer)
//
//            Log.i("ActivityRead", "ReadThread:接收到origin数据：" + Arrays.toString(buffer) + ";" + getXor(temp))
//
//            Log.i("ActivityReadTemp", "ReadThread:接收到处理过的数据：" + Arrays.toString(temp) + ";" + String(temp, 0, temp.size) + ";" + Arrays.toString(a) + ";" + String(a, 0, a.size))
//
//            val str = String(buffer, 0, size).split("S", "e").toString().trim()
//
//            Log.i("ActivityReadStr", "ReadThread:接收到数据：$str")
//
            tv.text = String(it, 3, 9)

            Log.i("ActivityReadStr", "接收到数据：" + Arrays.toString(it) + "；质量：" + String(it, 3, 9) + "；校验：" + Utils.checkLegal(it) + "；")

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        serialPortController.destroy()
    }

    private fun getXor(datas: ByteArray): Byte {

        var temp = datas[0]

        for (i in 1 until datas.size) {
            temp = temp xor datas[i]
        }

        return temp
    }

    private fun formatData(buffer: ByteArray): ByteArray {

        val list = ArrayList<Byte>()

        buffer.forEach {

            if (it.toInt() in 32..126) {
                list.add(it)
            }

        }

        return list.toByteArray()
    }

}
